<template>
  <div class="app-container">
    <el-row>
      <!--用户数据-->
      <el-col :span="24" :xs="24">
        <el-form
          :model="queryParams"
          ref="queryRef"
          :inline="true"
          v-show="showSearch"
          label-width="68px"
          :label-position="isPhone ? 'top' : 'left'"
        >
          <el-form-item label="学生姓名" prop="userName">
            <el-input
              v-model="queryParams.userName"
              placeholder="请输入学生姓名"
              clearable
              style="width: 240px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="培养领域" prop="trainField">
            <el-select
              v-model="queryParams.trainField"
              placeholder="请选择培养领域"
              clearable
              style="width: 240px"
            >
              <el-option
                v-for="dict in specialty"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="培养类别" prop="trainType">
            <el-select
              v-model="queryParams.trainType"
              placeholder="请选择培养类别"
              clearable
              style="width: 240px"
            >
              <el-option
                v-for="dict in training_category"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="高校名称" prop="trainUniversity">
            <el-select
              v-model="queryParams.trainUniversity"
              placeholder="请选择高校名称"
              clearable
              filterable
              style="width: 240px"
            >
              <el-option
                v-for="dict in university"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="培养专业" prop="trainMajor">
            <el-input
              v-model="queryParams.trainMajor"
              placeholder="请输入培养专业"
              clearable
              style="width: 240px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="入学年份" prop="trainStartYear">
            <el-select
              v-model="queryParams.trainStartYear"
              placeholder="请选择入学年份"
              clearable
              style="width: 240px"
            >
              <el-option
                v-for="year in yearOptions"
                :key="year"
                :label="year + '年'"
                :value="year"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="培养单位" prop="trainDeptId">
            <el-select
              v-model="queryParams.trainDeptId"
              placeholder="请选择培养单位"
              clearable
              style="width: 240px"
            >
              <el-option
                v-for="dict in trainingUnitList"
                :key="dict.deptId"
                :label="dict.deptName"
                :value="dict.deptId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="培养阶段" prop="trainStatus">
            <el-select
              v-model="queryParams.trainStatus"
              placeholder="请选择培养阶段"
              clearable
              style="width: 240px"
            >
              <el-option
                v-for="dict in train_progress"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="Plus"
              @click="handleAdd"
              v-hasRole="['admin', 'enterprise_group_admin']"
              >新增</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="Delete"
              :disabled="multiple"
              @click="handleDelete"
              v-hasRole="['admin', 'enterprise_group_admin']"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="Download"
              @click="handleExport"
              v-hasPermi="['system:user:export']"
              >导出</el-button
            >
          </el-col>
          <right-toolbar
            v-model:showSearch="showSearch"
            @queryTable="handleGetList"
            :columns="columns"
          ></right-toolbar>
        </el-row>

        <el-table
          v-loading="loading"
          :data="studentList"
          @selection-change="handleSelectionChange"
          height="calc(100vh - 320px)"
        >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column
            label="用户编号"
            align="center"
            key="userId"
            prop="userId"
            v-if="columns[0].visible"
            width="80"
          />
          <el-table-column
            label="姓名"
            align="center"
            key="nickName"
            prop="nickName"
            v-if="columns[2].visible"
            :show-overflow-tooltip="true"
            width="100"
          />
          <el-table-column
            label="账号"
            align="center"
            key="userName"
            prop="userName"
            v-if="columns[1].visible"
            :show-overflow-tooltip="true"
            width="120"
          />
          <el-table-column
            label="培养领域"
            align="center"
            key="trainField"
            prop="trainField"
            v-if="columns[3].visible"
            :show-overflow-tooltip="true"
            width="120"
          >
            <template #default="scope">
              {{ getTrainFieldText(scope.row.trainField) }}
            </template>
          </el-table-column>
          <el-table-column
            label="培养类别"
            align="center"
            key="trainType"
            prop="trainType"
            v-if="columns[4].visible"
            :show-overflow-tooltip="true"
            width="120"
          >
            <template #default="scope">
              {{ getTrainTypeText(scope.row.trainType) }}
            </template>
          </el-table-column>
          <el-table-column
            label="高校名称"
            align="center"
            key="trainUniversity"
            prop="trainUniversity"
            v-if="columns[5].visible"
            :show-overflow-tooltip="true"
            width="150"
          >
            <template #default="scope">
              {{ getUniversityText(scope.row.trainUniversity) }}
            </template>
          </el-table-column>
          <el-table-column
            label="培养专业"
            align="center"
            key="trainMajor"
            prop="trainMajor"
            v-if="columns[6].visible"
            :show-overflow-tooltip="true"
            width="150"
          />
          <el-table-column
            label="入学时间"
            align="center"
            key="trainStartDate"
            prop="trainStartDate"
            v-if="columns[7].visible"
            width="120"
          />
          <el-table-column
            label="学制"
            align="center"
            key="trainYear"
            prop="trainYear"
            v-if="columns[12].visible"
            width="80"
          >
            <template #default="scope">
              {{ getTrainYearText(scope.row.trainYear) }}
            </template>
          </el-table-column>
          <el-table-column
            label="培养单位"
            align="center"
            key="trainDeptName"
            prop="trainDeptName"
            v-if="columns[8].visible"
            :show-overflow-tooltip="true"
            width="150"
          >
          </el-table-column>
          <el-table-column
            label="培养阶段"
            align="center"
            key="trainStatus"
            prop="trainStatus"
            v-if="columns[9].visible"
            width="100"
          >
            <template #default="scope">
              <el-tag :type="getTrainStatusType(scope.row.trainStatus)">
                {{ getTrainStatusText(scope.row.trainStatus) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            label="手机号码"
            align="center"
            key="phonenumber"
            prop="phonenumber"
            v-if="columns[10].visible"
            width="120"
          />
          <el-table-column
            label="邮箱"
            align="center"
            key="email"
            prop="email"
            v-if="columns[11].visible"
            :show-overflow-tooltip="true"
            width="150"
          />
          <el-table-column
            label="毕业时间"
            align="center"
            key="trainStartEnd"
            prop="trainStartEnd"
            v-if="columns[13].visible"
            width="120"
          />
          <el-table-column
            label="创建时间"
            align="center"
            prop="createTime"
            v-if="columns[14].visible"
            width="160"
          >
            <template #default="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="审核状态"
            align="center"
            key="approvalStatus"
            prop="approvalStatus"
            v-if="columns[15].visible"
            width="100"
          >
            <template #default="scope">
              <el-tag :type="getApprovalStatusType(scope.row.approvalStatus)">
                {{ getApprovalStatusText(scope.row.approvalStatus) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="160"
            fixed="right"
            class-name="small-padding fixed-width"
          >
            <template #default="scope">
              <el-tooltip content="详情" placement="top">
                <el-button
                  link
                  type="info"
                  icon="View"
                  @click="handleDetail(scope.row)"
                ></el-button>
              </el-tooltip>
              <el-tooltip content="修改" placement="top">
                <el-button
                  link
                  type="primary"
                  icon="Edit"
                  @click="handleUpdate(scope.row)"
                  v-hasRole="[
                    'admin',
                    'enterprise_group_admin',
                    'student',
                    'enterprise_depart_admin',
                    'enterprise_unit_admin',
                  ]"
                ></el-button>
              </el-tooltip>
              <el-tooltip content="删除" placement="top">
                <el-button
                  link
                  type="primary"
                  icon="Delete"
                  @click="handleDelete(scope.row)"
                  v-hasRole="['admin', 'enterprise_group_admin']"
                ></el-button>
              </el-tooltip>
              <el-tooltip
                content="提交"
                placement="top"
                v-if="
                  scope.row.approvalStatus === 'no_submit' ||
                  scope.row.approvalStatus === 'rejected'
                "
              >
                <el-button
                  link
                  type="warning"
                  icon="Upload"
                  @click="handleSubmit(scope.row)"
                  v-hasRole="[
                    'student',
                    'enterprise_depart_admin',
                    'enterprise_unit_admin',
                  ]"
                ></el-button>
              </el-tooltip>
              <el-tooltip
                content="审批"
                placement="top"
                v-if="scope.row.approvalAuth"
              >
                <el-button
                  link
                  type="success"
                  icon="Check"
                  @click="handleApprove(scope.row)"
                  v-hasRole="['enterprise_group_admin']"
                ></el-button>
              </el-tooltip>
              <el-tooltip content="重置密码" placement="top">
                <el-button
                  link
                  type="primary"
                  icon="Key"
                  @click="handleResetPwd(scope.row)"
                  v-hasRole="['enterprise_group_admin']"
                ></el-button>
              </el-tooltip>
              <el-tooltip
                :content="scope.row.status === '0' ? '禁用' : '启用'"
                placement="top"
              >
                <el-button
                  link
                  :type="scope.row.status === '0' ? 'danger' : 'success'"
                  :icon="scope.row.status === '0' ? 'Lock' : 'Unlock'"
                  @click="handleStatusChange(scope.row)"
                  v-hasRole="['admin', 'enterprise_group_admin']"
                ></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="handleGetList"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改学生配置对话框 -->
    <el-dialog
      :title="isDetailMode ? '学生详情' : title"
      v-model="open"
      width="1200px"
      append-to-body
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form
        :model="form"
        :rules="rules"
        ref="userRef"
        label-width="160px"
        :label-position="isPhone ? 'top' : 'left'"
      >
        <el-collapse v-model="activeCollapseItems" accordion>
          <!-- 基本信息 -->
          <el-collapse-item title="基本信息" name="basic">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item
                  v-if="form.userId == undefined"
                  label="账号"
                  prop="userName"
                >
                  <el-input
                    v-model="form.userName"
                    placeholder="请输入账号"
                    maxlength="30"
                    :disabled="isDetailMode"
                    :readonly="isFieldReadonly"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item
                  v-if="form.userId == undefined"
                  label="密码"
                  prop="password"
                >
                  <el-input
                    v-model="form.password"
                    placeholder="请输入密码"
                    type="password"
                    maxlength="20"
                    show-password
                    :readonly="isFieldReadonly"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="姓名" prop="nickName">
                  <el-input
                    v-model="form.nickName"
                    placeholder="请输入姓名"
                    maxlength="30"
                    :disabled="!isFieldEditable('nickName')"
                    :readonly="isFieldReadonly"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="性别" prop="sex">
                  <el-radio-group
                    v-model="form.sex"
                    :disabled="!isFieldEditable('sex') || isDetailMode"
                  >
                    <el-radio
                      v-for="dict in sys_user_sex"
                      :key="dict.value"
                      :label="dict.value"
                      >{{ dict.label }}</el-radio
                    >
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="民族" prop="nation">
                  <el-select
                    filterable
                    v-model="form.nation"
                    placeholder="请选择民族"
                    style="width: 100%"
                    :disabled="!isFieldEditable('nation') || isDetailMode"
                  >
                    <el-option
                      v-for="dict in nation"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="身份证号" prop="idCard">
                  <el-input
                    v-model="form.idCard"
                    placeholder="请输入身份证号"
                    maxlength="18"
                    :disabled="!isFieldEditable('idCard')"
                    :readonly="isFieldReadonly"
                    @blur="handleIdCardChange"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="手机号码" prop="phonenumber">
                  <el-input
                    v-model="form.phonenumber"
                    placeholder="请输入手机号码"
                    maxlength="11"
                    :disabled="!isFieldEditable('phonenumber')"
                    :readonly="isFieldReadonly"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="邮箱" prop="email">
                  <el-input
                    v-model="form.email"
                    placeholder="请输入邮箱"
                    maxlength="50"
                    :disabled="!isFieldEditable('email')"
                    :readonly="isFieldReadonly"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="籍贯" prop="origin">
                  <el-input
                    v-model="form.origin"
                    placeholder="请输入籍贯"
                    maxlength="50"
                    :disabled="!isFieldEditable('origin')"
                    :readonly="isFieldReadonly"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="政治面貌" prop="political">
                  <el-select
                    v-model="form.political"
                    placeholder="请选择政治面貌"
                    style="width: 100%"
                    :disabled="!isFieldEditable('political') || isDetailMode"
                  >
                    <el-option
                      v-for="dict in political_status"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="出生日期" prop="birthday">
                  <el-input
                    disabled
                    v-model="previewBirthday"
                    placeholder="根据身份证号自动计算"
                    readonly
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="年龄" prop="age">
                  <el-input
                    disabled
                    v-model="previewAge"
                    placeholder="根据身份证号自动计算"
                    readonly
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="紧急联系人" prop="emergencyContact">
                  <el-input
                    v-model="form.emergencyContact"
                    placeholder="请输入紧急联系人"
                    maxlength="20"
                    :disabled="!isFieldEditable('emergencyContact')"
                    :readonly="isFieldReadonly"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item
                  label="紧急联系人联系方式"
                  prop="emergencyPhonenumber"
                >
                  <el-input
                    v-model="form.emergencyPhonenumber"
                    placeholder="请输入紧急联系人电话"
                    maxlength="11"
                    :disabled="!isFieldEditable('emergencyPhonenumber')"
                    :readonly="isFieldReadonly"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="家庭住址" prop="address">
                  <el-input
                    v-model="form.address"
                    placeholder="请输入家庭住址"
                    :readonly="isFieldReadonly"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="照片" prop="avatar">
                  <image-upload
                    v-model="form.avatar"
                    :limit="1"
                    :fileSize="50"
                    :fileType="['png', 'jpg', 'jpeg']"
                    :disabled="!isFieldEditable('avatar')"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-collapse-item>

          <!-- 工程硕博士试点项目信息 -->
          <el-collapse-item title="工程硕博士试点项目信息" name="train">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="工程硕博士培养领域" prop="trainField">
                  <el-select
                    v-model="form.trainField"
                    placeholder="请选择培养领域"
                    style="width: 100%"
                    :disabled="!isFieldEditable('trainField') || isDetailMode"
                  >
                    <el-option
                      v-for="dict in specialty"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="工程硕博士培养类别" prop="trainType">
                  <el-select
                    v-model="form.trainType"
                    placeholder="请选择培养类别"
                    style="width: 100%"
                    :disabled="!isFieldEditable('trainType') || isDetailMode"
                  >
                    <el-option
                      v-for="dict in training_category"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="工程硕博士高校名称" prop="trainUniversity">
                  <el-select
                    v-model="form.trainUniversity"
                    placeholder="请选择高校名称"
                    style="width: 100%"
                    filterable
                    :disabled="
                      !isFieldEditable('trainUniversity') || isDetailMode
                    "
                  >
                    <el-option
                      v-for="dict in university"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="工程硕博士学院名称" prop="trainCollege">
                  <el-input
                    v-model="form.trainCollege"
                    placeholder="请输入学院名称"
                    maxlength="100"
                    :disabled="!isFieldEditable('trainCollege')"
                    :readonly="isFieldReadonly"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="工程硕博士培养专业" prop="trainMajor">
                  <el-input
                    v-model="form.trainMajor"
                    placeholder="请输入培养专业"
                    maxlength="100"
                    :disabled="!isFieldEditable('trainMajor')"
                    :readonly="isFieldReadonly"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="工程硕博士入学时间" prop="trainStartDate">
                  <el-date-picker
                    v-model="form.trainStartDate"
                    type="date"
                    placeholder="选择入学时间"
                    value-format="YYYY-MM-DD"
                    style="width: 100%"
                    :disabled="
                      !isFieldEditable('trainStartDate') || isDetailMode
                    "
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="研究生学制" prop="trainYear">
                  <el-select
                    v-model="form.trainYear"
                    placeholder="请选择学制"
                    style="width: 100%"
                    :disabled="!isFieldEditable('trainYear') || isDetailMode"
                  >
                    <el-option
                      v-for="dict in graduate_education_system"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item
                  label="工程硕博士生计划毕业时间"
                  prop="trainStartEnd"
                >
                  <el-date-picker
                    v-model="form.trainStartEnd"
                    type="date"
                    placeholder="选择毕业时间"
                    value-format="YYYY-MM-DD"
                    style="width: 100%"
                    :disabled="
                      !isFieldEditable('trainStartEnd') || isDetailMode
                    "
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="当前处于培养阶段" prop="trainStatus">
                  <el-select
                    v-model="form.trainStatus"
                    placeholder="请选择培养阶段"
                    style="width: 100%"
                    :disabled="!isFieldEditable('trainStatus') || isDetailMode"
                  >
                    <el-option
                      v-for="dict in train_progress"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item
                  label="毕业后是否留在中国一汽工作"
                  prop="graduateStay"
                >
                  <el-radio-group
                    v-model="form.graduateStay"
                    :disabled="!isFieldEditable('graduateStay') || isDetailMode"
                  >
                    <el-radio
                      v-for="dict in sys_yes_no"
                      :key="dict.value"
                      :label="dict.value"
                      >{{ dict.label }}</el-radio
                    >
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
          </el-collapse-item>

          <!-- 本科学历信息 -->
          <el-collapse-item title="本科学历信息" name="graduate">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item
                  label="本科毕业高校名称"
                  prop="graduateUniversity"
                >
                  <el-select
                    v-model="form.graduateUniversity"
                    placeholder="请选择本科高校名称"
                    style="width: 100%"
                    filterable
                    :disabled="
                      !isFieldEditable('graduateUniversity') || isDetailMode
                    "
                  >
                    <el-option
                      v-for="dict in university"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="本科毕业学院名称" prop="graduateCollege">
                  <el-input
                    v-model="form.graduateCollege"
                    placeholder="请输入本科学院名称"
                    maxlength="100"
                    :disabled="!isFieldEditable('graduateCollege')"
                    :readonly="isFieldReadonly"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="本科专业" prop="graduateMajor">
                  <el-input
                    v-model="form.graduateMajor"
                    placeholder="请输入本科专业"
                    maxlength="100"
                    :disabled="!isFieldEditable('graduateMajor')"
                    :readonly="isFieldReadonly"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="本科毕业时间" prop="graduateStartEnd">
                  <el-date-picker
                    v-model="form.graduateStartEnd"
                    type="date"
                    placeholder="选择本科毕业时间"
                    value-format="YYYY-MM-DD"
                    style="width: 100%"
                    :disabled="
                      !isFieldEditable('graduateStartEnd') || isDetailMode
                    "
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-collapse-item>

          <!-- 研究生学历信息（只有在职博士填写） -->
          <el-collapse-item
            v-if="form.trainType === 'on-the-job_doctor'"
            title="研究生学历信息（只有在职博士填写）"
            name="master"
          >
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item
                  label="研究生毕业高校名称"
                  prop="masterUniversity"
                >
                  <el-select
                    v-model="form.masterUniversity"
                    placeholder="请选择研究生高校名称"
                    style="width: 100%"
                    filterable
                    :disabled="
                      !isFieldEditable('masterUniversity') || isDetailMode
                    "
                  >
                    <el-option
                      v-for="dict in university"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="研究生毕业学院名称" prop="masterCollege">
                  <el-input
                    v-model="form.masterCollege"
                    placeholder="请输入研究生学院名称"
                    maxlength="100"
                    :disabled="!isFieldEditable('masterCollege')"
                    :readonly="isFieldReadonly"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="研究生专业" prop="masterMajor">
                  <el-input
                    v-model="form.masterMajor"
                    placeholder="请输入研究生专业"
                    maxlength="100"
                    :disabled="!isFieldEditable('masterMajor')"
                    :readonly="isFieldReadonly"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="研究生毕业时间" prop="masterStartEnd">
                  <el-date-picker
                    v-model="form.masterStartEnd"
                    type="date"
                    placeholder="选择研究生毕业时间"
                    value-format="YYYY-MM-DD"
                    style="width: 100%"
                    :disabled="
                      !isFieldEditable('masterStartEnd') || isDetailMode
                    "
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-collapse-item>

          <!-- 培养单位管理员和培养部门管理员额外字段 -->
          <el-collapse-item title="实践信息" name="practice">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="培养单位" prop="trainDeptId">
                  <el-select
                    v-model="form.trainDeptId"
                    placeholder="请选择培养单位"
                    style="width: 100%"
                    :disabled="!isFieldEditable('trainDeptId') || isDetailMode"
                    @change="handleTrainDeptChange"
                  >
                    <el-option
                      v-for="dict in trainingUnitList"
                      :key="dict.deptId"
                      :label="dict.deptName"
                      :value="dict.deptId"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="实践部门" prop="practiceDeptId">
                  <el-select
                    v-model="form.practiceDeptId"
                    placeholder="请选择实践部门"
                    style="width: 100%"
                    :disabled="
                      !isFieldEditable('practiceDeptId') || isDetailMode
                    "
                  >
                    <el-option
                      v-for="dict in practiceDeptList"
                      :key="dict.deptId"
                      :label="dict.deptName"
                      :value="dict.deptId"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="实践地点" prop="practiceAddress">
                  <el-cascader
                    v-model="form.practiceAddress"
                    :disabled="
                      !isFieldEditable('practiceAddress') || isDetailMode
                    "
                    :options="regionOptions"
                    :props="cascaderProps"
                    placeholder="请选择省市区"
                    style="width: 100%"
                    clearable
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="入企实践开始时间" prop="joinStartDate">
                  <el-date-picker
                    v-model="form.joinStartDate"
                    type="date"
                    placeholder="选择入企实践开始时间"
                    value-format="YYYY-MM-DD"
                    style="width: 100%"
                    :disabled="
                      !isFieldEditable('joinStartDate') || isDetailMode
                    "
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="入企实践结束时间" prop="joinEntDate">
                  <el-date-picker
                    v-model="form.joinEntDate"
                    type="date"
                    placeholder="选择入企实践结束时间"
                    value-format="YYYY-MM-DD"
                    style="width: 100%"
                    :disabled="!isFieldEditable('joinEntDate') || isDetailMode"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="入企实践课题名称" prop="joinEntTopicName">
                  <el-input
                    v-model="form.joinEntTopicName"
                    placeholder="请输入入企实践课题名称"
                    maxlength="200"
                    :disabled="!isFieldEditable('joinEntTopicName')"
                    :readonly="isFieldReadonly"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item
                  label="入企实践课题简介"
                  prop="joinEntTopicIntroduction"
                >
                  <el-input
                    v-model="form.joinEntTopicIntroduction"
                    type="textarea"
                    placeholder="请输入入企实践课题简介"
                    :rows="4"
                    :disabled="!isFieldEditable('joinEntTopicIntroduction')"
                    :readonly="isFieldReadonly"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-collapse-item>

          <!-- 其他信息 -->
          <el-collapse-item title="其他信息" name="other">
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="备注" prop="remark">
                  <el-input
                    v-model="form.remark"
                    type="textarea"
                    placeholder="请输入备注"
                    :rows="4"
                    :disabled="!isFieldEditable('remark')"
                    :readonly="isFieldReadonly"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-collapse-item>
        </el-collapse>
        <el-form-item
          label="审核意见"
          prop="approvalRemark"
          style="margin-bottom: 0"
          v-if="form.approvalStatus === 'rejected'"
        >
          <el-input
            v-model="form.approvalRemark"
            disabled
            type="textarea"
            placeholder="请输入审核意见"
            :rows="3"
            style="width: 100%"
            :readonly="isFieldReadonly"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <!-- 详情模式按钮 -->
          <template v-if="isDetailMode">
            <el-button @click="cancel">关 闭</el-button>
          </template>

          <!-- 审批模式下的审核意见字段 -->
          <div v-else-if="title === '审批学生'" style="margin-bottom: 20px">
            <el-form-item
              label="审核意见"
              prop="approvalRemark"
              style="margin-bottom: 0"
            >
              <el-input
                v-model="form.approvalRemark"
                type="textarea"
                placeholder="请输入审核意见"
                :rows="3"
                style="width: 100%"
                :readonly="isFieldReadonly"
              ></el-input>
            </el-form-item>
          </div>

          <!-- 普通编辑模式按钮 -->
          <template v-else-if="title !== '审批学生'">
            <el-button
              type="primary"
              @click="submitForm"
              :loading="submitLoading"
              :disabled="submitLoading"
              >确 定</el-button
            >
            <el-button
              v-hasRole="[
                'student',
                'enterprise_depart_admin',
                'enterprise_unit_admin',
              ]"
              v-if="
                form.approvalStatus === 'no_submit' ||
                form.approvalStatus === 'rejected'
              "
              type="primary"
              @click="saveAndSubmit"
              :loading="saveSubmitLoading"
              :disabled="saveSubmitLoading"
              >保存并提交</el-button
            >
            <el-button @click="cancel">取 消</el-button>
          </template>

          <!-- 审批模式按钮 -->
          <template v-else>
            <el-button
              type="success"
              @click="handleApprovePass"
              :loading="approvePassLoading"
              :disabled="approvePassLoading"
              >通 过</el-button
            >
            <el-button
              type="danger"
              @click="handleApproveReject"
              :loading="approveRejectLoading"
              :disabled="approveRejectLoading"
              >驳 回</el-button
            >
            <el-button @click="cancel">取 消</el-button>
          </template>
        </div>
      </template>
    </el-dialog>

    <!-- 新增学生对话框 -->
    <el-dialog
      title="新增学生"
      v-model="addOpen"
      width="800px"
      append-to-body
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form
        :model="addForm"
        :rules="addRules"
        ref="addFormRef"
        label-width="160px"
        :label-position="isPhone ? 'top' : 'left'"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="账号" prop="userName">
              <el-input
                v-model="addForm.userName"
                placeholder="请输入账号"
                maxlength="30"
                :readonly="isFieldReadonly"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="密码" prop="password">
              <el-input
                v-model="addForm.password"
                placeholder="请输入密码"
                type="password"
                maxlength="20"
                show-password
                :readonly="isFieldReadonly"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名" prop="nickName">
              <el-input
                v-model="addForm.nickName"
                placeholder="请输入姓名"
                maxlength="30"
                :readonly="isFieldReadonly"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工程硕博士培养领域" prop="trainField">
              <el-select
                v-model="addForm.trainField"
                placeholder="请选择培养领域"
                style="width: 100%"
                :disabled="isDetailMode"
              >
                <el-option
                  v-for="dict in specialty"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工程硕博士培养类别" prop="trainType">
              <el-select
                v-model="addForm.trainType"
                placeholder="请选择培养类别"
                style="width: 100%"
                :disabled="isDetailMode"
              >
                <el-option
                  v-for="dict in training_category"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工程硕博士高校名称" prop="trainUniversity">
              <el-select
                v-model="addForm.trainUniversity"
                placeholder="请选择高校名称"
                style="width: 100%"
                filterable
                :disabled="isDetailMode"
              >
                <el-option
                  v-for="dict in university"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工程硕博士入学时间" prop="trainStartDate">
              <el-date-picker
                v-model="addForm.trainStartDate"
                type="date"
                placeholder="选择入学时间"
                value-format="YYYY-MM-DD"
                style="width: 100%"
                :disabled="isDetailMode"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="实践地点" prop="practiceAddress">
              <el-cascader
                v-model="addForm.practiceAddress"
                :options="regionOptions"
                :props="cascaderProps"
                placeholder="请选择省市区"
                style="width: 100%"
                clearable
                :disabled="isDetailMode"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="培养单位" prop="trainDeptId">
              <el-select
                v-model="addForm.trainDeptId"
                placeholder="请选择培养单位"
                style="width: 100%"
                :disabled="!isFieldEditable('trainDeptId') || isDetailMode"
                @change="handleTrainDeptChange"
              >
                <el-option
                  v-for="dict in trainingUnitList"
                  :key="dict.deptId"
                  :label="dict.deptName"
                  :value="dict.deptId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="实践部门" prop="practiceDeptId">
              <el-select
                v-model="addForm.practiceDeptId"
                placeholder="请选择实践部门"
                style="width: 100%"
                :disabled="!isFieldEditable('practiceDeptId') || isDetailMode"
              >
                <el-option
                  v-for="dict in practiceDeptList"
                  :key="dict.deptId"
                  :label="dict.deptName"
                  :value="dict.deptId"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            type="primary"
            @click="submitAddForm"
            :loading="addFormLoading"
            :disabled="addFormLoading"
            >确 定</el-button
          >
          <el-button @click="cancelAdd">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="User">
import { getList, addItem, editItem, delItem, getDetail, updateUserStatus } from "@/api/student";
import { getRegionTree } from "@/api/common";
import { submitApproval, handleApproval } from "@/api/approval";
import { getTrainingUnitList, getPracticeDeptList } from "@/api/system/dept";
import { resetUserPwd } from "@/api/system/user";
import ImageUpload from "@/components/ImageUpload/index.vue";
import useUserStore from "@/store/modules/user";
import { isPhone } from "@/utils/index";
import { yearOptions } from "@/utils/constant";

const router = useRouter();
const { proxy } = getCurrentInstance();
const {
  sys_normal_disable,
  sys_user_sex,
  nation,
  political_status,
  specialty,
  training_category,
  university,
  graduate_education_system,
  train_progress,
  sys_yes_no,
} = proxy.useDict(
  "sys_normal_disable",
  "sys_user_sex",
  "nation",
  "political_status",
  "specialty",
  "training_category",
  "university",
  "graduate_education_system",
  "train_progress",
  "sys_yes_no"
);

const studentList = ref([]);
const open = ref(false);
const addOpen = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const dateRange = ref([]);
const initPassword = ref(undefined);
const activeCollapseItems = ref(["basic"]);
const isDetailMode = ref(false);

// 按钮loading状态
const submitLoading = ref(false);
const saveSubmitLoading = ref(false);
const addFormLoading = ref(false);
const approvePassLoading = ref(false);
const approveRejectLoading = ref(false);
// 地区数据
const regionTree = ref([]);
const regionOptions = ref([]);
const trainingUnitList = ref([]);
const practiceDeptList = ref([]);
// 级联选择器配置
const cascaderProps = {
  value: "extId",
  label: "extName",
  children: "children",
  expandTrigger: "hover",
  //   checkStrictly: true // 任意选择一级
};

// 字段权限配置
const fieldPermissions = {
  // 集团管理员可以编辑所有字段
  enterprise_group_admin: {
    editable: true,
    fields: "all",
  },
  // 超级管理员可以编辑所有字段
  admin: {
    editable: true,
    fields: "all",
  },
  // 学生可以编辑的字段
  student: {
    editable: true,
    fields: [
      "sex",
      "nation",
      "idCard",
      "phonenumber",
      "email",
      "origin",
      "political",
      "birthday",
      "emergencyContact",
      "emergencyPhonenumber",
      "avatar",
      "graduateUniversity",
      "graduateCollege",
      "graduateMajor",
      "graduateStartEnd",
      "masterUniversity",
      "masterCollege",
      "masterMajor",
      "masterStartEnd",
      "remark",
    ],
    // 学生角色不可编辑的字段
    readonlyFields: [
      "nickName",
      "trainField",
      "trainType",
      "trainUniversity",
      "trainDeptId",
      "trainMajor",
      "trainStartDate",
      "trainYear",
      "trainStartEnd",
      "trainStatus",
      "graduateStay",
      "practiceDeptId",
      "practiceAddress",
      "joinStartDate",
      "joinEntDate",
      "joinEntTopicName",
      "joinEntTopicIntroduction",
    ],
  },
  // 培养单位管理员可以编辑的字段（包含学生字段 + 额外字段）
  enterprise_unit_admin: {
    editable: true,
    fields: "all",
    // 培养单位管理员不可编辑的字段
    readonlyFields: [
      "nickName",
      "trainField",
      "trainType",
      "trainUniversity",
      "trainStartDate",
      "trainDeptId",
      "practiceAddress",
    ],
  },
  // 培养部门管理员可以编辑的字段（与培养单位管理员相同）
  enterprise_depart_admin: {
    editable: true,
    fields: "all",
    // 培养部门管理员不可编辑的字段
    readonlyFields: [
      "nickName",
      "trainField",
      "trainType",
      "trainUniversity",
      "trainStartDate",
      "trainDeptId",
      "practiceAddress",
    ],
  },
};
// 列显隐信息
const columns = ref([
  { key: 14, label: `用户编号`, visible: true },
  { key: 0, label: `姓名`, visible: true },
  { key: 15, label: `账号`, visible: true },
  { key: 1, label: `培养领域`, visible: true },
  { key: 2, label: `培养类别`, visible: true },
  { key: 3, label: `高校名称`, visible: true },
  { key: 4, label: `培养专业`, visible: true },
  { key: 5, label: `入学时间`, visible: true },
  { key: 10, label: `学制`, visible: true },
  { key: 6, label: `培养单位`, visible: true },
  { key: 7, label: `培养阶段`, visible: true },
  { key: 8, label: `手机号码`, visible: true },
  { key: 9, label: `邮箱`, visible: true },
  { key: 11, label: `毕业时间`, visible: true },
  { key: 12, label: `创建时间`, visible: true },
  { key: 13, label: `审核状态`, visible: true },
]);

const data = reactive({
  form: {},
  addForm: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userName: undefined,
    trainField: undefined,
    trainType: undefined,
    trainUniversity: undefined,
    trainMajor: undefined,
    trainStartYear: undefined,
    trainDeptId: undefined,
    trainStatus: undefined,
  },
  addRules: {
    userName: [
      { required: true, message: "账号不能为空", trigger: "blur" },
      {
        min: 2,
        max: 20,
        message: "账号长度必须介于 2 和 20 之间",
        trigger: "blur",
      },
    ],
    nickName: [{ required: true, message: "姓名不能为空", trigger: "blur" }],
    password: [
      { required: true, message: "用户密码不能为空", trigger: "blur" },
      {
        min: 5,
        max: 20,
        message: "用户密码长度必须介于 5 和 20 之间",
        trigger: "blur",
      },
      {
        pattern: /^[^<>"'|\\]+$/,
        message: "不能包含非法字符：< > \" ' \\\ |",
        trigger: "blur",
      },
    ],
    trainField: [
      { required: true, message: "请选择培养领域", trigger: "change" },
    ],
    trainType: [
      { required: true, message: "请选择培养类别", trigger: "change" },
    ],
    trainUniversity: [
      { required: true, message: "请选择高校名称", trigger: "change" },
    ],
    trainStartDate: [
      { required: true, message: "请选择入学时间", trigger: "change" },
    ],
    trainDeptId: [
      { required: true, message: "请选择培养单位", trigger: "change" },
    ],
    practiceAddress: [
      { required: true, message: "请选择实践地点", trigger: "change" },
    ],
  },
});

const { queryParams, form, addForm, addRules } = toRefs(data);

const rules = computed(() => {
  const userStore = useUserStore();
  if (userStore.roles?.includes("student")) {
    return {
      userName: [
        { required: true, message: "账号不能为空", trigger: "blur" },
        {
          min: 2,
          max: 20,
          message: "账号长度必须介于 2 和 20 之间",
          trigger: "blur",
        },
      ],
      nickName: [{ required: false, message: "姓名不能为空", trigger: "blur" }],
      password: [
        { required: true, message: "用户密码不能为空", trigger: "blur" },
        {
          min: 5,
          max: 20,
          message: "用户密码长度必须介于 5 和 20 之间",
          trigger: "blur",
        },
        {
          pattern: /^[^<>"'|\\]+$/,
          message: "不能包含非法字符：< > \" ' \\\ |",
          trigger: "blur",
        },
      ],
      phonenumber: [
        { required: true, message: "手机号码不能为空", trigger: "blur" },
        {
          pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
          message: "请输入正确的手机号码",
          trigger: "blur",
        },
      ],
      email: [
        { required: true, message: "邮箱不能为空", trigger: "blur" },
        { type: "email", message: "请输入正确的邮箱地址", trigger: "blur" },
      ],
      emergencyPhonenumber: [
        {
          required: true,
          message: "紧急联系人联系方式不能为空",
          trigger: "blur",
        },
        {
          pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
          message: "请输入正确的紧急联系人手机号码",
          trigger: "blur",
        },
      ],
      origin: [{ required: true, message: "籍贯不能为空", trigger: "blur" }],
      emergencyContact: [
        { required: true, message: "紧急联系人不能为空", trigger: "blur" },
      ],
      avatar: [{ required: true, message: "照片不能为空", trigger: "change" }],
      graduateUniversity: [
        {
          required: true,
          message: "请选择本科毕业高校名称",
          trigger: "change",
        },
      ],
      graduateCollege: [
        {
          required: true,
          message: "本科毕业学院名称不能为空",
          trigger: "blur",
        },
      ],
      graduateMajor: [
        { required: true, message: "本科专业不能为空", trigger: "blur" },
      ],
      graduateStartEnd: [
        { required: true, message: "请选择本科毕业时间", trigger: "change" },
      ],
      masterUniversity: [
        {
          required: true,
          message: "请选择研究生毕业高校名称",
          trigger: "change",
        },
      ],
      masterCollege: [
        {
          required: true,
          message: "研究生毕业学院名称不能为空",
          trigger: "blur",
        },
      ],
      masterMajor: [
        { required: true, message: "研究生专业不能为空", trigger: "blur" },
      ],
      masterStartEnd: [
        { required: true, message: "请选择研究生毕业时间", trigger: "change" },
      ],
      sex: [{ required: true, message: "请选择性别", trigger: "change" }],
      nation: [{ required: true, message: "请选择民族", trigger: "change" }],
      political: [
        { required: true, message: "请选择政治面貌", trigger: "change" },
      ],
      idCard: [
        { required: true, message: "身份证号不能为空", trigger: "blur" },
        {
          pattern:
            /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
          message: "请输入正确的身份证号码",
          trigger: "blur",
        },
      ],
      trainStatus: [
        { required: false, message: "请选择培养阶段", trigger: "change" },
      ],
      trainField: [
        { required: false, message: "请选择培养领域", trigger: "change" },
      ],
      trainType: [
        { required: false, message: "请选择培养类别", trigger: "change" },
      ],
      trainUniversity: [
        { required: false, message: "请选择高校名称", trigger: "change" },
      ],
      trainYear: [
        { required: false, message: "请选择学制", trigger: "change" },
      ],
    };
  } else {
    return {
      trainCollege: [
        {
          required: false,
          message: "请输入工程硕博士学院名称",
          trigger: "change",
        },
      ],
      trainMajor: [
        {
          required: false,
          message: "请输入工程硕博士培养专业",
          trigger: "change",
        },
      ],
      trainYear: [
        { required: false, message: "请选择工程硕博士学制", trigger: "change" },
      ],
      trainStartEnd: [
        {
          required: false,
          message: "请选择工程硕博士毕业时间",
          trigger: "change",
        },
      ],
      trainStatus: [
        {
          required: false,
          message: "请选择工程硕博士培养阶段",
          trigger: "change",
        },
      ],
      graduateStay: [
        {
          required: false,
          message: "请选择毕业后是否留在中国一汽工作",
          trigger: "change",
        },
      ],
      joinStartDate: [
        { required: false, message: "请选择实践开始时间", trigger: "change" },
      ],
      joinEntDate: [
        { required: false, message: "请选择实践结束时间", trigger: "change" },
      ],
      joinEntTopicName: [
        { required: false, message: "请输入实践课题名称", trigger: "change" },
      ],
      joinEntTopicIntroduction: [
        { required: false, message: "请输入实践课题简介", trigger: "change" },
      ],
    };
  }
});

const checkKeyList = [
  "trainCollege",
  "trainMajor",
  "trainYear",
  "trainStartEnd",
  "trainStatus",
  "graduateStay",
  "joinStartDate",
  "joinEntDate",
  "joinEntTopicName",
  "joinEntTopicIntroduction",
];

// 培养阶段相关函数
const getTrainStatusType = (status) => {
  const statusMap = {
    在校学习: "success",
    在企实践: "warning",
    毕业: "info",
  };
  return statusMap[status] || "info";
};

const getTrainStatusText = (status) => {
  if (!status) return "";
  const dict = train_progress.value?.find((item) => item.value === status);
  return dict ? dict.label : status;
};

// 培养领域文本显示函数
const getTrainFieldText = (field) => {
  if (!field) return "";
  const dict = specialty.value?.find((item) => item.value === field);
  console.log(dict, specialty.value);
  return dict ? dict.label : field;
};

// 培养类别文本显示函数
const getTrainTypeText = (type) => {
  if (!type) return "";
  const dict = training_category.value?.find((item) => item.value === type);
  return dict ? dict.label : type;
};

// 学制文本显示函数
const getTrainYearText = (year) => {
  if (!year) return "";
  const dict = graduate_education_system.value?.find(
    (item) => item.value === year
  );
  return dict ? dict.label : year;
};

// 高校名称文本显示函数
const getUniversityText = (universityValue) => {
  if (!universityValue) return "未知";
  const dict = university.value?.find((item) => item.value === universityValue);
  return dict ? dict.label : universityValue;
};

// 学院名称文本显示函数
const getCollegeText = (college) => {
  return trainingUnitList.value.find((item) => +item.id === +college)?.label;
};

// 审核状态文本显示函数
const getApprovalStatusText = (status) => {
  const statusMap = {
    no_submit: "待提交",
    in_progress: "审核中",
    approved: "审核通过",
    rejected: "驳回",
  };
  return statusMap[status] || "未知";
};

// 审核状态标签类型函数
const getApprovalStatusType = (status) => {
  const typeMap = {
    no_submit: "info",
    in_progress: "warning",
    approved: "success",
    rejected: "danger",
  };
  return typeMap[status] || "info";
};

// 加载地区数据
const loadRegionData = async () => {
  try {
    const response = await getRegionTree();
    regionTree.value = response.data;
    regionOptions.value = response.data;
  } catch (error) {
    console.error("加载地区数据失败:", error);
    proxy.$modal.msgError("加载地区数据失败");
  }
};

// 获取当前用户角色
const getCurrentUserRole = () => {
  const userStore = useUserStore();
  return userStore.roles?.[0] || "student";
};

// 检查字段是否可编辑
const isFieldEditable = (fieldName) => {
  // 详情模式下所有字段都不可编辑
  if (isDetailMode.value) {
    return false;
  }

  const currentRole = getCurrentUserRole();
  const permission = fieldPermissions[currentRole];

  if (!permission || !permission.editable) {
    return false;
  }

  // 检查是否在只读字段列表中
  if (
    permission.readonlyFields &&
    permission.readonlyFields.includes(fieldName)
  ) {
    return false;
  }

  if (permission.fields === "all") {
    return true;
  }

  return permission.fields.includes(fieldName);
};

// 检查字段是否为只读模式
const isFieldReadonly = computed(() => {
  return isDetailMode.value;
});

// 根据身份证号计算出生日期和年龄
const calculateBirthInfo = (idCard) => {
  if (!idCard || idCard.length !== 18) {
    return { birthday: "", age: "" };
  }

  const year = idCard.substring(6, 10);
  const month = idCard.substring(10, 12);
  const day = idCard.substring(12, 14);

  const birthday = `${year}-${month}-${day}`;
  const today = new Date();
  const birthDate = new Date(year, month - 1, day);
  const age = today.getFullYear() - birthDate.getFullYear();

  return { birthday, age };
};

const previewAge = ref(0);
const previewBirthday = ref("");

// 监听身份证号变化
const handleIdCardChange = () => {
  if (form.value.idCard) {
    const { birthday, age } = calculateBirthInfo(form.value.idCard);
    previewAge.value = age;
    previewBirthday.value = birthday;
  }
};

/** 查询用户列表 */
function handleGetList() {
  loading.value = true;
  getList(proxy.addDateRange(queryParams.value, dateRange.value)).then(
    (res) => {
      loading.value = false;
      studentList.value = res.rows;
      total.value = res.total;
    }
  );
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  handleGetList();
}
/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}
/** 删除按钮操作 */
function handleDelete(row) {
  const userIds = row.userId || ids.value;
  proxy.$modal
    .confirm('是否确认删除用户编号为"' + userIds + '"的数据项？')
    .then(function () {
      return delItem(userIds);
    })
    .then(() => {
      handleGetList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}
/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "biz/mdtUserInfo/export",
    {
      ...queryParams.value,
    },
    `student_${new Date().getTime()}.xlsx`
  );
}
/** 选择条数  */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.userId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}
/** 重置操作表单 */
function reset() {
  form.value = {
    userId: undefined,
    userName: undefined,
    nickName: undefined,
    password: undefined,
    phonenumber: undefined,
    email: undefined,
    sex: undefined,
    status: "0",
    remark: undefined,
    // 基本信息
    idCard: undefined,
    birthday: undefined,
    nation: undefined,
    origin: undefined,
    political: undefined,
    emergencyContact: undefined,
    emergencyPhonenumber: undefined,
    avatar: undefined,
    // 工程硕博士培养信息
    trainStatus: undefined,
    trainField: undefined,
    trainType: undefined,
    trainUniversity: undefined,
    trainDeptId: undefined,
    trainMajor: undefined,
    trainYear: undefined,
    trainStartDate: undefined,
    trainStartEnd: undefined,
    graduateStay: undefined,
    // 本科信息
    graduateUniversity: undefined,
    graduateCollege: undefined,
    graduateMajor: undefined,
    graduateStartEnd: undefined,
    // 硕士信息
    masterUniversity: undefined,
    masterCollege: undefined,
    masterMajor: undefined,
    masterStartEnd: undefined,
    // 实践信息
    practiceDeptId: undefined,
    practiceAddress: [],
    joinStartDate: undefined,
    joinEntDate: undefined,
    joinEntTopicName: undefined,
    joinEntTopicIntroduction: undefined,
  };
  activeCollapseItems.value = ["basic"];
  proxy.resetForm("userRef");
}
/** 取消按钮 */
function cancel() {
  open.value = false;
  isDetailMode.value = false;
  reset();
}
/** 新增按钮操作 */
function handleAdd() {
  resetAddForm();
  addOpen.value = true;
}
/** 重置新增表单 */
function resetAddForm() {
  addForm.value = {
    userName: undefined,
    password: undefined,
    nickName: undefined,
    trainField: undefined,
    trainType: undefined,
    trainUniversity: undefined,
    trainStartDate: undefined,
    trainDeptId: undefined,
    practiceDeptId: undefined,
    practiceAddress: [],
  };
  proxy.resetForm("addFormRef");
}
/** 取消新增 */
function cancelAdd() {
  addOpen.value = false;
  resetAddForm();
}
/** 提交新增表单 */
function submitAddForm() {
  // 防止重复提交
  if (addFormLoading.value) return;

  proxy.$refs["addFormRef"].validate((valid) => {
    if (valid) {
      addFormLoading.value = true;
      addItem({
        ...addForm.value,
        practiceAddress: addForm.value.practiceAddress.join(","),
      })
        .then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          addOpen.value = false;
          handleGetList();
        })
        .catch((error) => {
          console.error("新增失败:", error);
        })
        .finally(() => {
          addFormLoading.value = false;
        });
    }
  });
}
/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  isDetailMode.value = false;
  const userId = row.userId || ids.value;
  previewAge.value = 0;
  previewBirthday.value = "";
  getDetail(userId).then((response) => {
    form.value = {
      ...response.data,
      practiceAddress: response.data.practiceAddress
        ? response.data.practiceAddress.split(",")
        : [],
    };
    handleIdCardChange();
    handleTrainDeptChange(response.data.trainDeptId);
    open.value = true;
    title.value = "修改学生";
  });
}

/** 提交按钮 */
function submitForm() {
  // 防止重复提交
  if (submitLoading.value) return;

  proxy.$refs["userRef"].validate((valid) => {
    if (valid) {
      submitLoading.value = true;
      const params = {
        ...form.value,
        practiceAddress: form.value.practiceAddress.join(","),
      };
      if (form.value.userId != undefined) {
        editItem(params)
          .then((response) => {
            proxy.$modal.msgSuccess("修改成功");
            open.value = false;
            handleGetList();
          })
          .catch((error) => {
            console.error("修改失败:", error);
          })
          .finally(() => {
            submitLoading.value = false;
          });
      } else {
        addItem(params)
          .then((response) => {
            proxy.$modal.msgSuccess("新增成功");
            open.value = false;
            handleGetList();
          })
          .catch((error) => {
            console.error("新增失败:", error);
          })
          .finally(() => {
            submitLoading.value = false;
          });
      }
    } else {
      proxy.$modal.msgError("请填写必填项");
    }
  });
}

function saveAndSubmit() {
  // 防止重复提交
  if (saveSubmitLoading.value) return;

  proxy.$refs["userRef"].validate((valid) => {
    if (valid) {
      if (checkKeyList.some((key) => !form.value[key])) {
        proxy.$modal.msgError("请填写完所有信息后再提交");
        return;
      }
      saveSubmitLoading.value = true;
      const params = {
        ...form.value,
        practiceAddress: form.value.practiceAddress.join(","),
      };
      editItem(params)
        .then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          submitApproval({
            businessId: form.value.userId,
            approvalTypeCode: "student_infor_flow",
            approvalInfo: JSON.stringify(form.value)
          });
        })
        .catch((error) => {
          console.error("保存并提交失败:", error);
        })
        .finally(() => {
          saveSubmitLoading.value = false;
        });
    } else {
      proxy.$modal.msgError("请填写必填项");
    }
  });
}

// 提交审核
function handleSubmit(row) {
  if (checkKeyList.some((key) => !row[key])) {
    proxy.$modal.msgError("请填写完所有信息后再提交");
    return;
  }
  const userId = row.userId || ids.value;
  proxy.$modal
    .confirm("是否确认提交审核？")
    .then(function () {
      return submitApproval({
        businessId: userId,
        approvalTypeCode: "student_infor_flow",
        approvalInfo: JSON.stringify(row)
      });
    })
    .then(() => {
      handleGetList();
      proxy.$modal.msgSuccess("提交成功");
    })
    .catch(() => {});
}

// 审批操作
function handleApprove(row) {
  reset();
  isDetailMode.value = false;
  const userId = row.userId || ids.value;
  getDetail(userId).then((response) => {
    form.value = {
      ...response.data,
      practiceAddress: response.data.practiceAddress
        ? response.data.practiceAddress.split(",")
        : [],
      approvalRemark: "",
    };
    handleIdCardChange();
    handleTrainDeptChange(response.data.trainDeptId);
    open.value = true;
    title.value = "审批学生";
  });
}

// 通过审批
function handleApprovePass() {
  // 防止重复提交
  if (approvePassLoading.value) return;

  approvePassLoading.value = true;
  const approvalData = {
    //  approvalId: form.value.userId,
    approvalInfoId: form.value.approvalInfoId,
    approvalNodeId: form.value.approvalNodeId,
    approvalStatus: "approved",
    remark: form.value.approvalRemark,
  };

  handleApproval(approvalData)
    .then(() => {
      proxy.$modal.msgSuccess("审批通过");
      open.value = false;
      handleGetList();
    })
    .catch((error) => {
      console.error("审批通过失败:", error);
    })
    .finally(() => {
      approvePassLoading.value = false;
    });
}

// 驳回审批
function handleApproveReject() {
  if (!form.value.approvalRemark) {
    proxy.$modal.msgError("请填写审核意见");
    return;
  }

  // 防止重复提交
  if (approveRejectLoading.value) return;

  approveRejectLoading.value = true;
  const approvalData = {
    approvalInfoId: form.value.approvalInfoId,
    approvalNodeId: form.value.approvalNodeId,
    approvalStatus: "rejected",
    remark: form.value.approvalRemark,
  };

  handleApproval(approvalData)
    .then(() => {
      proxy.$modal.msgSuccess("已驳回");
      open.value = false;
      handleGetList();
    })
    .catch((error) => {
      console.error("审批驳回失败:", error);
    })
    .finally(() => {
      approveRejectLoading.value = false;
    });
}

/** 重置密码按钮操作 */
function handleResetPwd(row) {
  proxy
    .$prompt('请输入"' + row.userName + '"的新密码', "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      closeOnClickModal: false,
      closeOnPressEscape: false,
      inputPattern: /^.{5,20}$/,
      inputErrorMessage: "用户密码长度必须介于 5 和 20 之间",
      inputValidator: (value) => {
        if (/<|>|"|'|\||\\/.test(value)) {
          return "不能包含非法字符：< > \" ' \\\ |";
        }
      },
    })
    .then(({ value }) => {
      resetUserPwd(row.userId, value).then((response) => {
        proxy.$modal.msgSuccess("修改成功，新密码是：" + value);
      });
    })
    .catch(() => {});
}

function queryTrainingUnitList() {
  getTrainingUnitList().then((res) => {
    trainingUnitList.value = res.data;
  });
}

function handleTrainDeptChange(val) {
  if (!val) {
    practiceDeptList.value = [];
    return;
  }
  getPracticeDeptList(val).then((res) => {
    practiceDeptList.value = res.data;
  });
}

/** 详情按钮操作 */
function handleDetail(row) {
  reset();
  const userId = row.userId;
  isDetailMode.value = true;
  previewAge.value = 0;
  previewBirthday.value = "";

  getDetail(userId).then((response) => {
    form.value = {
      ...response.data,
      practiceAddress: response.data.practiceAddress
        ? response.data.practiceAddress.split(",")
        : [],
    };
    handleIdCardChange();
    handleTrainDeptChange(response.data.trainDeptId);
    open.value = true;
    title.value = "学生详情";
  });
}

/** 状态修改 */
function handleStatusChange(row) {
  const newStatus = row.status === '0' ? '1' : '0'
  const statusText = newStatus === '0' ? '启用' : '禁用'
  
  proxy.$modal
    .confirm(`确认要${statusText}"${row.userName}"吗？`, "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      closeOnClickModal: false,
      closeOnPressEscape: false,
    })
    .then(() => {
      return updateUserStatus({
        userId: row.userId,
        status: newStatus,
      })
    })
    .then(() => {
      handleGetList()
      proxy.$modal.msgSuccess(`${statusText}成功`)
    })
    .catch(() => {})
}

// 初始化数据
loadRegionData();
queryTrainingUnitList();
handleGetList();
</script>
